import { AddressApi } from "@/api";
import { defineStore } from "pinia";
import { ref } from 'vue'


export default defineStore("address", () => {
    const listMain = ref<Vm.Address[]>([])
    const isDefaultId = ref<number>()
    const isInit = ref<boolean>(false)
    const init = async () => {
        if (isInit.value) return
        isInit.value = true
        listMain.value = await AddressApi.getlist()
        const DefaultAddress = await AddressApi.getdefault()
        isDefaultId.value = DefaultAddress.id
    }

    const removeHandler = async (id: number) => {
        await AddressApi.remove(id)
        const i = listMain.value.findIndex(item => item.id === id)
        listMain.value.splice(i, 1)
    }
    const editHandler = async (data: HttpPayload.AddressCRUD) => {
        await AddressApi.edit(data)
        const i = listMain.value.findIndex(item => item.id === data.id)
        listMain.value.splice(i, 1, data)
        // //目前的id的isDefault的id为正在编辑的id的话直接return
        if (data.isDefault && isDefaultId.value !== data.id) {
            await AddressApi.setdefault(data.id)
            listMain.value.forEach(item => {
                item.isDefault = 0
                if (item.id === data.id) {
                    item.isDefault = 1
                    isDefaultId.value = item.id
                }
            })

        } else return
    }
    const addHandler = async (data: HttpPayload.AddressCRUD) => {
        const id = await AddressApi.add(data)
        listMain.value.push({ ...data, id: id })
        if (data.isDefault && isDefaultId.value !== id) {
            await AddressApi.setdefault(id)
            listMain.value.forEach(item => {
                item.isDefault = 0
                if (item.id === id) {
                    item.isDefault = 1
                    isDefaultId.value = item.id
                } else return
            })
        } else return
    }
    return { listMain, init, isInit, addHandler, isDefaultId, editHandler, removeHandler }
}, {
    persist: {
        enabled: true
    }
})